package net.dl.ss.web;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.dl.ss.dao.EventDao;
import net.dl.ss.domain.Event;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author yakovlev.yuriy@gmail.com
 * @since 12.8.2008
 */
@Controller
public class EventsController extends BaseController {
	protected final Log logger = LogFactory.getLog(getClass());
	private final EventDao eventDao;

	@Autowired
	public EventsController(EventDao eventDao) {
		this.eventDao = eventDao;
	}
	
	@RequestMapping("/events.htm")
	public ModelAndView eventsHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, Object> model = new HashMap<String, Object>();
		return new ModelAndView("events", "model", model);
	}
	
	@RequestMapping("/eventsList.htm")
	protected void eventsListHandler(HttpServletRequest request, HttpServletResponse response) {
		logger.info("Getting events...");
		try {
			ServletOutputStream  os = response.getOutputStream();
			modifyResponseHeader(response, "text/xml");
			
		    os.println("<events>");
		    List<Event> events = this.eventDao.list(Event.class);
			for(Event event : events) {
		    	os.print(event.toXML());
		    }
			os.println("</events>");
	
			os.close();
		} catch (IOException e) {
			logger.error(e.getMessage());
		} 
	}
	
	@RequestMapping("/eventUpdate.htm")
	public void eventUpdateHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");

		Event event = new Event();
		event.setTitle(request.getParameter("title"));
		String date = request.getParameter("date");
		if(date!=null && !"".equals(date)) {
			try {
				SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yy");
				java.util.Date dt = sdf.parse(date);
				java.sql.Timestamp timestamp = new java.sql.Timestamp(dt.getTime());
				event.setDate(timestamp);
			} catch(ParseException ex) {
				logger.error(ex.getMessage());
			}
		}

		String type = request.getParameter("type");
		event.setType((type==null || "".equals(type)) ? null : Integer.parseInt(type));
		
		String rank = request.getParameter("rank");
		event.setRank((rank==null || "".equals(rank)) ? null : Integer.parseInt(rank));
		
		event.setPlace(request.getParameter("place"));
		event.setOrganizer(request.getParameter("organizer"));
		event.setMasterOfCeremony(request.getParameter("masterOfCeremony"));
		event.setChairman(request.getParameter("chairman"));
		event.setMusic(request.getParameter("music"));
		event.setScrutineer(request.getParameter("scrutineer"));
		event.setSupport(request.getParameter("support"));
		try {
			String id = request.getParameter("id");
			if(id!=null && !"".equals(id)) {
				event.setId(Long.parseLong(id));
				this.eventDao.updateEntity(event);
			} else {
				this.eventDao.saveEntity(event);
			}
			os.print("{success:true}");
		} catch(Exception ex) {
			logger.error(ex.getMessage());
		}
	
	    os.close();
	}
	
	@RequestMapping("/eventDelete.htm")
	public void eventDeleteHandler(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletOutputStream  os = response.getOutputStream();
		modifyResponseHeader(response, "text/plain");

		try {
			String id = request.getParameter("id");
			if(id!=null && !"".equals(id)) {
				this.eventDao.deleteEntityById(Long.parseLong(id));
			}
			os.print("{success:true}");
		} catch(Exception ex) {
			logger.error(ex.getMessage());
		}
	
	    os.close();
	}

}
